package com.btr.ivle.backgroud;

import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.DatabaseModuleItem;
import com.btr.ivle.helper.URLtoString;

public class GetModulesTask extends AsyncTask<Void, Void, Void>{
	
	private Context context;
	
	public GetModulesTask(Context context){
		this.context = context;
	}

	protected Void doInBackground(Void... voids) {
		String code, name, id, ay, sem, nNewAnnounc, mc;
		int forums, workbins, webcasts;
		boolean gradebooks, weblinks;
		String tableModule = IVLEToken.getUserID(), tableItem = IVLEToken.getUserID()+"_ModuleItem";
		ContentValues values;

		DatabaseModule dbModule = new DatabaseModule(this.context,IVLEToken.getUserID(),null, context.getResources().getInteger(R.integer.DBVersion));
		DatabaseModuleItem dbModuleItem = new DatabaseModuleItem(this.context,IVLEToken.getUserID()+"_ModuleItem",null, context.getResources().getInteger(R.integer.DBVersion));

		try{
        	URL url = new URL("https://ivle.nus.edu.sg/api/Lapi.svc/Modules?APIKey=" +
        			"daQmMJmIJndpP9mK4Om5T&AuthToken=" + IVLEToken.getToken() + "&Duration=0&IncludeAllInfo=true");
        	JSONObject jModule = new JSONObject(URLtoString.get(url));
	        JSONArray JArrayModule = jModule.getJSONArray("Results");
	        
	        dbModuleItem.getWritableDatabase().delete(tableItem, null, null);
	        dbModule.getWritableDatabase().delete(tableModule, null, null);
	        
	        for (int i = 0; i < JArrayModule.length(); i++) {
	        	id = JArrayModule.getJSONObject(i).getString("ID").toString();
	        	code = JArrayModule.getJSONObject(i).getString("CourseCode").toString();
	        	name = JArrayModule.getJSONObject(i).getString("CourseName").toString();
	        	ay = JArrayModule.getJSONObject(i).getString("CourseAcadYear").toString();
	        	sem = JArrayModule.getJSONObject(i).getString("CourseSemester").toString();
	        	mc = JArrayModule.getJSONObject(i).getString("CourseMC").toString();
	        	nNewAnnounc = JArrayModule.getJSONObject(i).getString("BadgeAnnouncement").toString();

	        	forums = JArrayModule.getJSONObject(i).optJSONArray("Forums").length();
	        	workbins = JArrayModule.getJSONObject(i).getJSONArray("Workbins").length();
	        	webcasts = JArrayModule.getJSONObject(i).getJSONArray("Webcasts").length();
	        	
	        	gradebooks = JArrayModule.getJSONObject(i).getBoolean("hasGradebookItems");
	        	weblinks = JArrayModule.getJSONObject(i).getBoolean("hasWeblinkItems");
	        	
	        	values = new  ContentValues();
	        	values.put(dbModule.colID, id);
	        	values.put(dbModule.colCode, code);
	        	values.put(dbModule.colName, name);
	        	values.put(dbModule.colAY, ay);
	        	values.put(dbModule.colSem, sem);
	        	values.put(dbModule.colNewAnnounce, nNewAnnounc);
	        	values.put(dbModule.colCourseMC, mc);
        		
	        	values.put(dbModule.colForums, forums);
    	        values.put(dbModule.colWorkbins, workbins);
    	        values.put(dbModule.colWebcasts, webcasts);
    	        
    	        values.put(dbModule.colGradebooks, gradebooks);
    	        values.put(dbModule.colWebLinks, weblinks);
    	        
    	        dbModule.getWritableDatabase().replace(tableModule, null, values);
    	        
    	        for(int j=0;j<workbins;j++){
    	        	values = new  ContentValues();
    	        	values = getItem("Workbin", code, 
    	        			JArrayModule.getJSONObject(i).optJSONArray("Workbins").getJSONObject(j), dbModuleItem);
    	        	dbModuleItem.getReadableDatabase().replace(tableItem, null, values);
    	        }
    	        for(int j=0;j<forums;j++){
    	        	values = new  ContentValues();
    	        	values = getItem("Forum", code, 
    	        			JArrayModule.getJSONObject(i).optJSONArray("Forums").getJSONObject(j), dbModuleItem);
    	        	dbModuleItem.getReadableDatabase().replace(tableItem, null, values);
    	        }
    	        for(int j=0;j<webcasts;j++){
    	        	values = new  ContentValues();
    	        	values = getItem("Webcast", code, 
    	        			JArrayModule.getJSONObject(i).optJSONArray("Webcasts").getJSONObject(j), dbModuleItem);
    	        	dbModuleItem.getReadableDatabase().replace(tableItem, null, values);
    	        }
    	        dbModule.close();
    	        dbModuleItem.close();
			}
        }catch(Exception ex){
	    }

		return null;
	}
	
    protected void onPostExecute(Void result) {
    	@SuppressWarnings("unchecked")
		AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete(""); 
    }
    
    private ContentValues getItem(String type, String code, JSONObject jObject, 
    		DatabaseModuleItem dbModuleItem) throws JSONException{
    	ContentValues values = new  ContentValues();
    	values.put(dbModuleItem.colCode, code);
    	values.put(dbModuleItem.colID, jObject.getString("ID").toString());
    	values.put(dbModuleItem.colName, jObject.getString("Title").toString());
    	values.put(dbModuleItem.colType, type);
    	values.put(dbModuleItem.colBadgeTool, jObject.getString("BadgeTool").toString());
    	return values;
    }

}
